package com.example.homelicaisystem.services.impl;

import com.example.homelicaisystem.dao.CardMapper;
import com.example.homelicaisystem.entity.Card;
import com.example.homelicaisystem.entity.Detail;
import com.example.homelicaisystem.entity.SelectResult;
import com.example.homelicaisystem.entity.exception.UsedCashException;
import com.example.homelicaisystem.services.CardService;
import com.example.homelicaisystem.utils.UserUtil;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CardImpl implements CardService {
private final CardMapper cardMapper;

    public CardImpl(CardMapper cardMapper) {
        this.cardMapper = cardMapper;
    }

    @Override
    public List<SelectResult> selectCard() {
        return cardMapper.select();
    }

    @Override
    public void increaseBank(Detail data) {
        int id = data.getCardId();
        Card card =  cardMapper.getCardById(id);
        card.setMoney(data.getMoney()+card.getMoney());
        cardMapper.updateCard(card);
    }

    @Override
    public void decreaseBank(Detail data) {
//        获取数据库中的银行卡信息
        Card card = cardMapper.getCardById(data.getCardId());
//        余额不足时，无法扣除金额
        if (card.getMoney() < data.getMoney()){
            throw new UsedCashException("金额错误");
        }else {
            card.setMoney(card.getMoney()-data.getMoney());
            cardMapper.updateCard(card);
        }
    }

    @Override
    public void createCard(Card data) {
        int userId = UserUtil.getUserId();
        data.setUserId(userId);
        data.setMoney(0);

        String bankName = data.getBankName();
        String cardNum = data.getCardNum();
        String cardName =bankName+ cardNum.substring(cardNum.length()-4,cardNum.length()) ;
        data.setCardName(cardName);
        cardMapper.insert(data);

    }
}
